/**
 * 
 */
package com.ar.myshares.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ar.myshares.model.Operation;
import com.ar.myshares.model.User;
import com.ar.myshares.services.OperationService;
import com.ar.myshares.services.UserService;

/**
 * @author Hernan
 *
 */
@Controller
public class OperationsController {

	@Autowired
	private OperationService operationService;

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/allOperations", method = RequestMethod.GET)
	public @ResponseBody List<Operation> getAllOperationsFrom(@RequestParam String userID) {
		User user = this.userService.getUser(Long.valueOf(userID).longValue());
		if (user != null) {
			return user.getOperations();
		}
		return null;
	}

	@RequestMapping(value = "/saveOperation", method = RequestMethod.POST)
	public void saveOperation(@RequestBody Operation operation, @RequestParam String userID) {
		operation.setId(-1);
		User loggedUser = this.userService.getUser(Long.valueOf(userID));
		if (loggedUser != null) {
			Operation savedOperation = this.operationService.saveOperation(operation);
			loggedUser.addNewOperation(savedOperation);
			this.userService.saveUser(loggedUser);
		}
	}

	@RequestMapping(value = "/removeOperation", method = RequestMethod.POST)
	public void removeOperation(@RequestParam String operationID) {
		Operation realOperation = this.operationService.getOperation(Long.valueOf(operationID).longValue());
		if (realOperation != null) {
			this.operationService.removeOperation(realOperation);
		}
	}

}
